<?php
require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
require_once dirname(__FILE__). '/util/util.php';
set_time_limit(360*60);
ini_set('memory_limit', '512M');

$g_start = microtime(true);

$dbconn = Connection::getInstance();

$userInfos = getUserInfos($dbconn);
$userInfos = useIdAsKey($userInfos);
traversalDirectoryFile($userInfos, RAW_DATA_ROOT);
//foreach($userInfos as $k=>$v){
	
//	if(isset($v['full_reg_time'])){
//		$userInfos[$k]['registrationToProfileTime'] = (($v['full_reg_time'] - $v['created']) / 60) . 'minutes' ;
//	}else{
//		$userInfos[$k]['registrationToProfileTime'] = '';
//	}
//	unset($userInfos[$k]['full_reg_time']);
	
//	if(isset($v['confirmed_coreg_time'])){
//		$userInfos[$k]['registrationToConfirmTime'] = (($v['confirmed_coreg_time'] - $v['created']) /60) . 'minutes';
//	}else{
//		$userInfos[$k]['registrationToConfirmTime'] = '';
//	}
//	unset($userInfos[$k]['confirmed_coreg_time']);	

//}
$csvHeader = array('uID', 'Name', 'Email', 'DOB', 'Age', 'Site', 'IP', 'Gender', 'Pixel fire', 'Tokens rewarded', 'Short reg co-reg', 'Long reg co-reg', 'Update co-reg', 'Confirm co-reg');
sendCsv($userInfos, $csvHeader, 'RegisterUser.csv');

echo 'Totally: '. (microtime(true) - $g_start) . " seconds \n";
echo "memory: " . memory_get_peak_usage() . " bytes \n";

function getUserInfos($db) 
{
	global $g_start;
	try{
		$siteSql = " SELECT id, name FROM sites ";
		$sites = $db->query($siteSql);
		$siteArr = array();
		foreach($sites as $val){
			$siteArr[$val['id']] = $val['name'];
		}
		
		$time_start = strtotime('2012-04-01 00:00:00');
		$time_end = strtotime('2012-05-01 00:00:00');
		$cam = " AND (cam = '17' OR cam = '18')";
		$pub = " AND (pub = 'CD46' OR pub = 'CD75' OR pub = 'CD2' OR pub = 'CD10137')";
		$sql = " SELECT id, concat(firstname, ' ', lastname)  as name, email, birthday, (YEAR(CURDATE())-YEAR(birthday)) - (RIGHT(CURDATE(),5)<RIGHT(birthday,5)) as age, site_id as site, ip, gender, fired, 0 as credits FROM users WHERE (created>=? AND created<?) ".$cam.$pub;
		$users = $db->query($sql, array($time_start, $time_end));
		echo "Total Users: " . count($users) . "\t" . (microtime(true) - $g_start) . "\n";
		$count = 0;
		foreach ($users as &$user)
		{
			$sql = 'select sum(credit) as credits from rewards where user_id=?';
			$result = $db->query($sql, array($user['id']));
			$user['site'] = $siteArr[$user['site']];
			$user['credits'] = $result[0]['credits']?$result[0]['credits']:0;
			$user['fired'] = ($user['fired'])?'Y':'N';
			$user['ip'] = long2ip($user['ip']);
			$count ++;
			if ($count % 5000 == 0)
			{
				echo "finished ". $count . "\t" . (microtime(true) - $g_start) . "\n";
			}
			$user['basic_reg_coreg_end'] = 0;
			$user['full_reg_coreg_end'] = 0;
			$user['profiling_coreg_end'] = 0;
			$user['confirm_coreg_end'] = 0;
		}
		return $users;
	}catch(Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function useIdAsKey($arr)
{
	$ret = array();
	foreach($arr as $k=>$v){
		$ret[$v['id']] = $v;
	}
	
	return $ret;
}

function traversalDirectoryFile(&$userInfos, $path)
{
	$handle = opendir($path);
	while($file = readdir($handle)){
  		if($file=="."||$file=="..")
   		continue;
  		$newFilePath = $path . DIRECTORY_SEPARATOR . $file;
  		if(is_dir($newFilePath)){
  			traversalDirectoryFile($userInfos, $newFilePath);
  		}
  		if(is_file($newFilePath)){
  			$file_handle = fopen($newFilePath, 'r');
  			if ($file_handle) {
				while (!feof($file_handle)) {
					$line = fgets($file_handle);
					if (!empty($line)) {
						$line_args = explode(':', $line);
						$time = isset($line_args[0])? $line_args[0] : 0;
						$session = isset($line_args[2])? $line_args[2] : '';
						$uid = isset($line_args[3])? $line_args[3] : '';
						$event = isset($line_args[4])? $line_args[4] : '';
						if(count($line_args) == 24){
							$monetization = isset($line_args[16])? $line_args[16] : 0;
							$won = isset($line_args[17])? $line_args[17] : 0;
							$token = isset($line_args[20])? $line_args[20] : 0;
						}else if(count($line_args) == 28){
							$monetization = isset($line_args[16])? $line_args[16] : 0;
							$won = isset($line_args[17])? $line_args[17] : 0;
							$token = isset($line_args[20])? $line_args[20] : 0;
						}else if(count($line_args) == 29){
							$monetization = isset($line_args[17])? $line_args[17] : 0;
							$won = isset($line_args[18])? $line_args[18] : 0;
							$token = isset($line_args[21])? $line_args[21] : 0;
						}else if(count($line_args) == 30){
							$monetization = isset($line_args[18])? $line_args[18] : 0;
							$won = isset($line_args[19])? $line_args[19] : 0;
							$token = isset($line_args[22])? $line_args[22] : 0;
						}else if(count($line_args) == 31){
							$monetization = isset($line_args[19])? $line_args[19] : 0;
							$won = isset($line_args[20])? $line_args[20] : 0;
							$token = isset($line_args[23])? $line_args[23] : 0;
						}else{
							$token = 0;
							$won = 0;
						}
						if(isset($userInfos[$uid])){
							/*$timeFrame = date('Y-m', $time);
							if($session != ''){
								if(!isset($userInfos[$uid]['sessionNum'][$timeFrame])){
									$userInfos[$uid]['sessionNum'][$timeFrame] = 1;
								}else{
									$userInfos[$uid]['sessionNum'][$timeFrame]++;
								}
							}
							
							if($won != 0 || $won != ''){
								if(!isset($userInfos[$uid]['wonNum'][$timeFrame])){
									$userInfos[$uid]['wonNum'][$timeFrame] = 1;
								}else{
									$userInfos[$uid]['wonNum'][$timeFrame]++;
								}
							}*/
							
							if($event == 'full_reg'){
								//$userInfos[$uid]['full_reg_time'] = $time;
								$userInfos[$uid]['full_reg_coreg_end'] = 1;
							}else if($event == 'basic_reg_coreg'){
								$userInfos[$uid]['basic_reg_coreg_end'] = 1;
							}else if($event == 'profiling_coreg_end'){
								$userInfos[$uid]['profiling_coreg_end'] = 1;
							}else if($event == 'confirm_coreg_end'){
								$userInfos[$uid]['confirm_coreg_end'] = 1;
							}else if($event == 'confirmed_coreg'){
								//$userInfos[$uid]['confirmed_coreg_time'] = $time;
							}
						}
					}
				}
				fclose($file_handle);
			}
  		}
 	}
 	closedir($handle);
}

function sendCsv($data, $headers, $filename) {
	$output = fopen(dirname(__FILE__) . DIRECTORY_SEPARATOR . $filename, 'w');
	fputcsv($output, $headers);
	if(!empty($data)){
		foreach ($data as $row) {
			fputcsv($output, $row);
		}			
	}

	
	fclose($output);
}